<?php

namespace Zms\Request\Driver;

use Zms\Request\Http;
use Zms\Request\RequestAbstract;
use Zms\Request\Result;

class Curl extends RequestAbstract
{
    public function execute(string $url, array $query = []): Result
    {
        try {
            $curl = curl_init();//开启CURL
            if ($this->method === 'GET') {
                curl_setopt($curl, CURLOPT_URL, $this->setLink($url, $query));//设置请求地址
            } elseif ($this->method === 'POST') {
                curl_setopt($curl, CURLOPT_URL, $url);//设置请求地址
                curl_setopt($curl, CURLOPT_POST, 1);
                if (!is_null($this->data)) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
                }
            }
            //返回结果,不直接显示
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

            /**
             * 设置headers
             */
            if (count($this->headers) > 0) {
                curl_setopt($curl, CURLOPT_HTTPHEADER, $this->getHeaders());
            }

            //设置请求COOKIE
            if (count($this->cookies) > 0) {
                curl_setopt($curl, CURLOPT_COOKIE, $this->getCookie());
            }


            //设置连接超时
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->timeout);

            //跳过https验证
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

            //是否返回响应头
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);//获取HTTP状态码
            curl_close($curl);
            return new Result((int)$httpCode, '请求完成', $result, Http::CURL);
        } catch (\Exception $exception) {
            return new Result(0, $exception->getMessage(), null, Http::CURL);
        }
    }


    /**
     * @describe 获取请求的headers
     * @user zlf <zms-pro@qq.com> 2025/3/13
     * @return array
     */
    private function getHeaders(): array
    {
        $headers = [];
        foreach ($this->headers as $name => $value) {

            $headers[] = "{$name}: {$value}";
        }
        return $headers;
    }

    /**
     * @describe 获取请求COOKIE
     * @user zlf <zms-pro@qq.com> 2025/3/13
     * @return string
     */
    public function getCookie(): string
    {
        $cookie = [];
        foreach ($this->cookies as $key => $value) {
            $cookie[] = "$key=$value";
        }
        return implode(';', $cookie);
    }
}